package com.zcy;

import com.espertech.esper.common.client.EventBean;
import com.espertech.esper.runtime.client.EPEventService;
import com.zcy.event.MyEvent;
import com.zcy.util.EsperBuilder;
import com.zcy.util.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;

/**
 * 14.3.20. Ranked Window (rank or ext:rank)
 * 需要注意排序窗口与排名窗口的区别：
 * TODO：排序窗口是全局性的Event替换
 * 而排名窗口中，除了保持全局性的Event替换，还要根据分组条件，保留最大/最小的一个。（仔细体会第一个方法运行结果的20，而Sort窗口则是30）
 */
@Slf4j
public class RankWindow extends TimeUtils {

    private static final String _RankWindow = "@name('rank-window') select sum(num) from MyEvent#ext:rank(amount, 2, num desc)";

    /**
     * sum is : 10
     * sum is : 20
     * sum is : 30
     * sum is : 50
     * sum is : 60
     * sum is : 70
     */
    @Test
    public void sortWinTest() {
        EsperBuilder esperBuilder = new EsperBuilder(_RankWindow, new Class[]{MyEvent.class});

        esperBuilder.startCompile();

        EPEventService epEventService = esperBuilder.startDeploy((eventBeans, eventBeans1, epStatement, epRuntime) -> {
            for (int i = 0; i < eventBeans.length; i++) {
                EventBean eventBean = eventBeans[i];
                log.info("sum is : {}", eventBean.get("sum(num)"));
            }
        });

        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("001").name("001-name").num(10).build(), MyEvent.class.getSimpleName());
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("001").name("001-name").num(20).build(), MyEvent.class.getSimpleName());
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("001").name("001-name").num(30).build(), MyEvent.class.getSimpleName());
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("002").name("002-name").num(20).build(), MyEvent.class.getSimpleName());
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("003").name("003-name").num(30).build(), MyEvent.class.getSimpleName());
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("004").name("004-name").num(40).build(), MyEvent.class.getSimpleName());

        sleep(TimeUnit.SECONDS, 40L);
    }


}
